/**
 * // Definition for a Node.
 * function Node(val, next) {
 *     this.val = val;
 *     this.next = next;
 * };
 */

import { ListNode as Node } from '../../helper/ListNode'

/**
 * @param {Node} head
 * @param {number} insertVal
 * @return {Node}
 */
export var insert = function (head, insertVal, firstHead = null) {
  if (!head) {
    head = new Node(insertVal)
    head.next = head
    return head
  }
  const next = head.next
  if (
    head === next ||
    firstHead === next ||
    (head.val <= insertVal && insertVal < next.val) ||
    (head.val > next.val && (insertVal >= head.val || insertVal <= next.val))
  ) {
    head.next = new Node(insertVal, next)
    return head
  }

  insert(next, insertVal, firstHead || head)
  return head
}
